import React from 'react'
import { useDispatch, useSelector } from 'react-redux';
import { addIterm,closemenus, changeshowmenu } from '@/store/modules/modules'
//引入EditorDragger
import EditorDragger from './EditorDragger/EditorDragger'
// 引入删除组件
import Deletemenu from './EditorDragger/ContextMenu'
function dragDropBox_center() {
  const dispatch = useDispatch();
  const colors = useSelector((state: any) => state.reducer.color)
  //获取仓库中侧边栏数据
  const componentsData = useSelector((state: any) => state.reducer.componentsData)
  // 获取仓库里画布拖得所有元素
  const componentList = useSelector((state: any) => state.reducer.componentList)
  //在放置目标上触发的事件=>必须要有=》否则无法触发拖动结束事件
  const dragover = (event: any) => {
    // 阻止默认行为以允许放置
    event.preventDefault();
  }
  //拖动结束
  const dropFun = (event: any) => {
    //计算拖动结束得位置得横坐标和纵坐标
    const { clientX, clientY } = event
    //获取画布元素
    const boxcanvas: any = document.querySelector('#box-canvas')
    //获取画布距离视口得位置坐标
    const { left: xx, top: yy } = boxcanvas.getBoundingClientRect()
    //计算拖动结束得时候 left和top
    let left = clientX - xx;
    let top = clientY - yy
    //获取容器里标记拖动元素得下标
    const index = event.dataTransfer.getData('index')
    //根据标记得下标  获取要拖得元素
    var datas = componentsData[index]
    const { width, height } = datas.style
    left -= width / 2
    top -= height / 2
    //拷贝
    var datass = JSON.parse(JSON.stringify(datas))
    //给datas 中style赋值
    datass.style = { ...datass.style, left, top }
    //放在仓库里面
    dispatch(addIterm(datass))
  }
  const showmenu = (event:any) => {
    //计算点击的left和top
    //获取画布
    const boxcanvas:any = document.querySelector('#box-canvas')
    //获取画布距离视口得位置坐标
    const { left: xx, top: yy } = boxcanvas.getBoundingClientRect()
    const { clientX, clientY } = event
    const left = clientX - xx
    const top = clientY - yy
    dispatch(changeshowmenu({ left, top }))
    // 阻止事件默认行为+-
    event.preventDefault();
  }
  //点击画布关闭右键菜单
  const closeMenu = () => {
    dispatch(closemenus())
  }
  return (
    <div id="box-canvas"
      style={{ height: '900px', background: `rgba(${colors.r},${colors.g},${colors.b},${colors.a})` }}
      onDrop={dropFun} onDragOver={dragover} onContextMenu={showmenu} onClick={closeMenu}>
      {
        componentList.map((item: any, index: any) => <EditorDragger key={index} element={item.payload}></EditorDragger>)
      }
      <Deletemenu />
    </div>
  )
}

export default dragDropBox_center
